<template>
  <div class="order-create">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <h2>创建订单</h2>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>产品信息</el-divider>

        <div v-for="(product, index) in formData.products" :key="index" class="product-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item
                :label="`产品名称 ${index + 1}`"
                :prop="`products.${index}.name`"
                :rules="rules.productName"
              >
                <el-input v-model="product.name" placeholder="请输入产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="`单价`" :prop="`products.${index}.price`" :rules="rules.price">
                <el-input-number
                  v-model="product.price"
                  :min="0"
                  :precision="2"
                  :step="10"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                :label="`数量`"
                :prop="`products.${index}.quantity`"
                :rules="rules.quantity"
              >
                <el-input-number
                  v-model="product.quantity"
                  :min="1"
                  :step="1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4" class="product-actions">
              <el-button type="danger" icon="Delete" circle @click="removeProduct(index)" />
            </el-col>
          </el-row>
        </div>

        <div class="add-product">
          <el-button type="primary" icon="Plus" @click="addProduct">添加产品</el-button>
        </div>

        <el-divider>订单信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单金额" prop="amount">
              <el-input-number
                v-model="formData.amount"
                :min="0"
                :precision="2"
                :step="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣" prop="discount">
              <el-input-number
                v-model="formData.discount"
                :min="0"
                :precision="2"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税费" prop="tax">
              <el-input-number
                v-model="formData.tax"
                :min="0"
                :precision="2"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择订单状态" style="width: 100%">
                <el-option label="待处理" value="pending" />
                <el-option label="处理中" value="processing" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Delete, Plus } from '@element-plus/icons-vue';
import { orderApi } from '@/api';

const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const formData = reactive({
  customerName: '',
  phone: '',
  email: '',
  address: '',
  products: [
    {
      name: '',
      price: 0,
      quantity: 1
    }
  ],
  amount: 0,
  discount: 0,
  tax: 0,
  remark: '',
  status: 'pending'
});

// 表单验证规则
const rules = reactive<FormRules>({
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  status: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
});

// 添加产品
const addProduct = () => {
  formData.products.push({
    name: '',
    price: 0,
    quantity: 1
  });
};

// 移除产品
const removeProduct = (index: number) => {
  if (formData.products.length > 1) {
    formData.products.splice(index, 1);
  } else {
    ElMessage.warning('至少需要一个产品');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;

      try {
        // 计算总金额
        const total = formData.amount - formData.discount + formData.tax;

        // 构建订单数据
        const orderData = {
          customer: {
            name: formData.customerName,
            phone: formData.phone,
            email: formData.email,
            address: formData.address
          },
          products: formData.products,
          amount: formData.amount,
          discount: formData.discount,
          tax: formData.tax,
          total,
          status: formData.status,
          remark: formData.remark
        };

        // 调用创建订单接口
        await orderApi.createOrder(orderData);

        ElMessage({
          message: '创建订单成功',
          type: 'success'
        });

        // 跳转到订单列表页
        router.push('/order/list');
      } catch (error: any) {
        ElMessage.error(error.message || '创建订单失败');
      } finally {
        loading.value = false;
      }
    } else {
      console.log('表单验证失败', fields);
    }
  });
};

// 重置表单
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();

  // 重置产品列表
  formData.products = [
    {
      name: '',
      price: 0,
      quantity: 1
    }
  ];
};
</script>

<style lang="scss" scoped>
.order-create {
  padding: 20px;

  .form-card {
    .card-header {
      h2 {
        margin: 0;
        font-size: 20px;
        color: var(--theme-text-color);
      }
    }
  }

  .order-form {
    .product-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px dashed var(--theme-border-color);
      border-radius: 4px;

      .product-actions {
        display: flex;
        align-items: flex-end;
        justify-content: center;
        height: 100%;
        padding-bottom: 20px;
      }
    }

    .add-product {
      margin-bottom: 20px;
      text-align: center;
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 30px;
    }
  }
}
</style>
